package com.qsmx.qingqiuticket.app.delegate;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateCouponListBinding;
import com.qsmx.qingqiuticket.app.delegate.adapter.CouponAdapter;
import com.qsmx.qingqiuticket.app.entity.CouponEntity;
import com.qsmx.qingqiuticket.app.event.CouponCheckRefreshEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;

public class CouponDelegate extends AtmosDelegate {
    private boolean flag;
    private DelegateCouponListBinding mBinding;
    private CouponAdapter mCouponAdapter;
    private CouponEntity mData;

    private String allMoney;
    private String mSelectCouponId;

    @Override
    public Object setLayout() {
        return R.layout.delegate_coupon_list;
    }

    public static CouponDelegate create(String totalPrice, String couponId) {

        final Bundle args = new Bundle();
        args.putString(FusionTag.TOTAL_PRICE, totalPrice);
        args.putString(FusionTag.COUPON_ID, couponId);
        final CouponDelegate delegate = new CouponDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            allMoney = args.getString(FusionTag.TOTAL_PRICE);
            mSelectCouponId = args.getString(FusionTag.COUPON_ID);
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        getCouponList();

        mBinding = DelegateCouponListBinding.bind(rootView);
        mBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportDelegate().pop();
            }
        });
        mCouponAdapter = new CouponAdapter(getContext());
        mBinding.rlvCouponList.setLayoutManager(new LinearLayoutManager(requireContext()));
        mBinding.rlvCouponList.setAdapter(mCouponAdapter);

        mBinding.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (mData != null && mData.getBody().size() > 0) {
                        Bundle bundle = new Bundle();
                        for (CouponEntity.BodyBean data : mData.getBody()) {
                            data.setSelect(false);
                            mCouponAdapter.notifyDataSetChanged();
                            bundle.putString(FusionTag.COUPON_ID, "");
                            bundle.putDouble(FusionTag.COUPON_PRICE, 0);
                        }
                        EventBus.getDefault().post(new CouponCheckRefreshEvent(bundle));
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString(FusionTag.COUPON_ID, "");
                        bundle.putDouble(FusionTag.COUPON_PRICE, 0);
                        EventBus.getDefault().post(new CouponCheckRefreshEvent(bundle));
                    }
                    getSupportDelegate().pop();
                }
            }
        });

        mBinding.tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (mData != null && mData.getBody().size() > 0) {
                        Bundle bundle = new Bundle();
                        for (CouponEntity.BodyBean data : mData.getBody()) {
                            if (data.isSelect()) {
                                bundle.putString(FusionTag.COUPON_ID, String.valueOf(data.getCouponRecordId()));
                                bundle.putDouble(FusionTag.COUPON_PRICE, data.getPrice());
                                flag = true;
                                break;
                            } else {
                                flag = false;
                            }
                        }
                        if (flag) {
                            EventBus.getDefault().post(new CouponCheckRefreshEvent(bundle));
                            getSupportDelegate().pop();
                        } else {
                            DialogUtil.showCardErrorDialog(getContext(), "请选择优惠券", "确定");
                        }
                    }
                }
            }
        });
    }

    private void getCouponList() {
        DialogUtil.showLoadingDialog(getContext(), "正在加载...");
        JSONObject params = new JSONObject();
        params.put("storeId", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM));
        params.put("goodsPrice", String.valueOf(allMoney));
        params.put("useRange", "1");
        params.put("memberUuid", FusionData.mMemData.getUserId());

        HttpHelper.RestClientPostRaw(params, HttpUrl.COUPON_LIST,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<CouponEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                if (mData.getBody().size() > 0) {
                                    for (CouponEntity.BodyBean data : mData.getBody()) {
                                        if (StringUtil.isNotEmpty(mSelectCouponId) && String.valueOf(data.getCouponRecordId()).equals(mSelectCouponId)) {
                                            data.setSelect(true);
                                        }
                                    }
                                    mCouponAdapter.setData(mData.getBody());
                                    mCouponAdapter.notifyDataSetChanged();
                                    mBinding.rlvCouponList.setVisibility(View.VISIBLE);
                                    mBinding.linHasNoCoupon.setVisibility(View.GONE);
                                } else {
                                    mBinding.rlvCouponList.setVisibility(View.GONE);
                                    mBinding.linHasNoCoupon.setVisibility(View.VISIBLE);
                                }
                            }
                        } catch (Exception e) {

                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                    }
                });

    }
}
